package com.jiashihui.schema_lgorithm.java.socket.handler.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 分拣信息服务处理器工厂
 */
@Component
public class ServiceHandlerFactory implements ApplicationListener<ServiceHandlerEvent> {
    private static final Logger LOGGER = LoggerFactory.getLogger(ServiceHandlerFactory.class);

    private static Map<ServiceTypeEnum, IServiceHandler> handlerMap = new ConcurrentHashMap<>();

    /**
     * 通过服务类型获取对应的处理器
     *
     * @param serviceType 服务类型
     * @return
     */
    public static IServiceHandler getHandler(int serviceType) {
        ServiceTypeEnum serviceTypeEnum = ServiceTypeEnum.getEnumById(serviceType);
        if (null == serviceTypeEnum) {
            LOGGER.warn("not found {} handler.", serviceType);
            return null;
        }
        return handlerMap.get(serviceTypeEnum);
    }

    /**
     * 注册绑定不同类型分拣服务对应的处理器
     *
     * @param handler 处理器
     */
    private void registerHandler(IServiceHandler handler) {
        ServiceTypeEnum serviceType = handler.getServiceType();
        LOGGER.info("开始绑定{}类型的分拣物流服务处理器", serviceType.getName());
        handlerMap.put(serviceType, handler);
    }

    @Override
    public void onApplicationEvent(ServiceHandlerEvent event) {
        IServiceHandler handler = (IServiceHandler) event.getSource();
        this.registerHandler(handler);
    }
}
